const getApps = getApp().globalData
const rate = wx.getSystemInfoSync().windowWidth / 750
const util = require('../../utils/util.js')
const Monitor = require('../../utils/monitor.js').Monitor
Page(Monitor.hookApp({
  data: {
    kongImage: false,
    idArr: [],
    testTime: 0,
    arr: [],
    lists: [],
    lock: true,
    totalMoney: 0,
    totalLength: 0,
    allChecked: false,
    rate,
    imgUrl: getApp().globalData.imgUrl,
    imgUrls: getApp().globalData.imgUrls,
    loading: true,
    pageNum: 1,
    showNum: 3,
    list: [],
    isSelect: "wm12sd1f5asf55dgfj45k48hgk765fh选中.svg",
    NOSelect: "wm22s1d5s54g5sh5f4j54y5j5f未选中.svg",
    Ncart: "wmdsf5dfh5hra5hjnfgcs购物车.svg",
    Ycart: "wx8651vthzawyfnfkuop购物车红.svg",
  },
  jumpDetails(e) {
    wx.redirectTo({
      url: '/pages/shopDetails/shopDetails?goods_id=' + e.currentTarget.dataset.item.goods_id
    })
  },
  onLoad: function(options) {
    this.cartList()
  },
  cartList() {
    var that = this
    util.API(
      'pyapi/googs_cart_list', {
        page: this.data.pageNum,
        pageshow: 100000
      }, 'application/x-www-form-urlencoded'
    ).then(res => {
      let {
        code,
        data,
        distribution_name,
        defaultIndex,
        count
      } = res
      distribution_name = JSON.stringify(distribution_name)
      data.forEach((item, index) => {
        var sku__sku_type = JSON.parse(item.sku__sku_type)
        var newguige = []
        sku__sku_type.map((item, index) => {
          for (prop in item) {
            newguige.push(item[prop])
          }
          // newGuige.push(items.val)
        })
        data[index].sku__sku_type = newguige
        item.waysArr = this.setWaysArr([], item.goods__distribution_type, distribution_name)
      })
      that.data.list = that.data.list.concat(data);
      that.setData({
        list: that.data.list,
        distribution_name,
        defaultIndex
      })

      if (that.data.list.length == 0) {
        that.setData({
          kongImage: true
        })

      } else {



      }
      that.locklock()
    })
  },


  setWaysArr(waysArr, distribution_type, distribution_name) { // 设置自定义配送信息
    distribution_type = distribution_type.split(',');
    distribution_name = JSON.parse(distribution_name)
    let len = distribution_type.length
    for (let i = 0; i < len; i++) {
      waysArr.push(distribution_name[distribution_type[i]])
    }
    return waysArr
  },




  locklock() {
    var that = this
    util.API('spwx/v1.Shop/continueLookLook', {

    }).then(res => {
      let {
        code,
        data
      } = res

      if (code == 200) {
        that.setData({
          lists: res.data.list,
        })
      }

    })
  },
  pay(e) {
    if (!this.data.lock) {
      return
    }
    var {
      arr
    } = this.data
    if (arr.length == 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      })
      return false
    }
    util.API('pyapi/create_order', {
      goods: JSON.stringify(arr),
      cart: JSON.stringify(this.data.idArr)
      // market_type: 0 //需要改
    }, 'application/x-www-form-urlencoded').then(res => {
      let {
        data,
        code,
        totalFee,
        msg
      } = res
      if (code == 200) {
        this.data.lock = false
        setTimeout(() => {
          this.data.lock = true
        }, 2000)
        console.log(data.distribution,'data.distribution')
        wx.navigateTo({
          url: `/pages/DingdanPay/DingdanPay?goods=${JSON.stringify(arr)}&code=${totalFee.code}&msg=${totalFee.msg}&distribution=${data.distribution}&activity_id=undefined&cart=${JSON.stringify(this.data.idArr)}&distribution_name=${this.data.distribution_name}&defaultIndex=${this.data.defaultIndex}`,
        })
      } else {
        wx.showToast({
          title: msg + '',
          icon: "none"
        })
      }

    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    // var query = wx.createSelectorQuery(), that = this;
    // query.select('.hints').boundingClientRect(function (rect) {

    //   that.setData({
    //     hintHeight: rect.height
    //   })
    // }).exec();

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  total() {
    var totalMoney = 0
    var totalLength = 0
    this.data.idArr = []
    this.data.arr = []
    this.data.list.map((item, index) => {
      if (item.ischecked) {
        this.data.idArr.push(item.id)
        totalMoney += item.need_pay * item.goods_stock;
        totalLength += item.goods_stock;
        var shop_json = {
          goods_id: item.goods__goods_id,
          goods_stock: item.goods_stock,
          sku: item.sku_id,
          uniqueKey: item.sku__uniqueKey
        };
        this.data.arr.push(shop_json)
      }
    })
    this.setData({
      totalMoney,
      totalLength
    })
    if (this.data.list.length == 0) {
      this.setData({
        kongImage: true,
        allChecked: false
      })
    }
  },
  allChecked() {
    if (this.data.list.length == 0) {
      wx.showToast({
        title: '暂无商品',
        icon: 'none',
      })
      return false
    }
    this.data.list.map((item, index) => {
      item.ischecked = !this.data.allChecked
    })
    this.setData({
      allChecked: !this.data.allChecked,
      list: this.data.list
    })
    this.total()
  },
  jumoShopD(e) {
    var index = e.currentTarget.dataset.index;
    wx.navigateTo({
      url: '/pages/shopDetails/shopDetails?goods_id=' + this.data.list[index].goods__goods_id,

    })
  },
  checkedImage(e) {
    var index = e.currentTarget.dataset.index
    var {
      list
    } = this.data
    var lists = 'list[' + index + '].ischecked'
    list[index].ischecked = list[index].ischecked ? false : true

    var listIsTrueLength = list.filter(tem => tem.ischecked == true)
    this.setData({
      allChecked: listIsTrueLength.length == list.length ? true : false
    })
    this.setData({
      [lists]: list[index].ischecked,
    })
    var listIsTrueLength = this.data.list.filter(tem => tem.ischecked == true)
    this.setData({
      allChecked: listIsTrueLength.length == list.length ? true : false
    })
    this.total()
  },
  shopNumChange(e) {
    var that = this
    var {
      list
    } = this.data, {
      index,
      type
    } = e.currentTarget.dataset;
    if (list.length == 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none',
      })
      return false
    }
    var lists = 'list[' + index + '].goods_stock';
    if (type == 'all') {
      var goods_id = JSON.stringify(getSkuIid(list))
      wx.showModal({
        title: '删除所选中商品?',
        showCancel: true,
        cancelText: '返回',
        cancelColor: '',
        confirmText: '删除',
        confirmColor: '',
        success: function(res) {
          if (res.confirm) {
            that.numChange(sku_id, goods_id, type, list, lists, index)
          }
        },
      })
    } else {
      var sku_id = list[index].sku_id;
      var goods_id = list[index].goods__goods_id;
      this.numChange(sku_id, goods_id, type, list, lists, index)
    }

    function getSkuIid(list) {
      var allshop = [];
      list.forEach((item, index) => {
        if (item.ischecked) {
          var allObj = {}
          allObj.goods_id = item.goods__goods_id
          allObj.sku_id = item.sku_id
          allObj.uniqueKey = item.sku__uniqueKey
          allObj.id = item.id
          allshop.push(allObj)
        }
      })
      return allshop
    }
  },
  numChange(sku_id, goods_id, type, list, lists, index) {
    var that = this


    util.API(
      'pyapi/Changing_Cart', {
        sku_id,
        goods_id,
        type
      }, 'application/x-www-form-urlencoded'
    ).then(res => {
      let {
        code,
        data
      } = res
      if (code == 200) {
        switch (type) {
          case 'del':
            list.splice(index, 1)
            that.setData({
              list,
            })
            wx.showToast({
              title: res.msg,
              icon: 'none',
            })
            break;
          case 'increase':
            that.setData({
              [lists]: list[index].goods_stock + 1
            })
            break;
          case 'reduce':
            var num = list[index].goods_stock
            if (num > 1) {
              that.setData({
                [lists]: num - 1
              })
            } else {
              wx.showToast({
                title: '购买商品数量不低于1',
                icon: 'none',
              })
            }
            break;
          case 'all':
            var newlist = []
            this.data.list.map((item, index) => {
              if (item.ischecked) {} else {
                newlist.push(item)
              }
            })
            that.setData({
              list: newlist
            })
            wx.showToast({
              title: res.msg,
              icon: 'none',
            })
            break;
            // default:
        }
        this.total()
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
        })
      }
    })
  },
  bindscrolltolower() {
    // this.data.pageNum++
    //   this.cartList()
  },
  touchS: function(e) {
    if (e.touches.length == 1) {
      this.data.startX = e.touches[0].clientX
      this.data.starty = e.touches[0].clientY
    }
  },
  touchM: function(e) {
    var that = this,
      index = e.currentTarget.dataset.index,
      list = that.data.list,
      {
        startX,
        starty
      } = this.data,
      etouches = e.touches[0];
    var lists = 'list[' + index + '].contentStyle';
    var angle = that.angle({
      X: startX,
      Y: starty
    }, {
      X: etouches.clientX,
      Y: etouches.clientY
    });
    this.data.angle = angle
    if (Math.abs(angle) > 20) {
      that.setData({
        [lists]: 0
      })
      return
    }
    if (e.touches.length == 1) {
      var disX = startX - etouches.clientX;
      if (disX < 0) {
        if (disX == 0) {
          this.setData({
            [lists]: 0
          });
          return
        }
        if (list[index].contentStyle != 0) {
          this.setData({
            [lists]: disX + 138
          });
        }
      } else {
        if (list[index].contentStyle >= 138) {
          return
        }
        if (disX <= 138)
          this.setData({
            [lists]: disX
          });
      }
    }
  },
  touchE: function(e) {
    var that = this
    var list = that.data.list;
    var index = e.currentTarget.dataset.index;
    if (e.changedTouches.length == 1 && Math.abs(that.data.angle) < 20) {
      var endX = e.changedTouches[0].clientX;
      var disX = that.data.startX - endX;
      if (disX < 0) {
        if (Math.abs(disX) > 2) {
          var contentStyle = Math.abs(disX) > 138 / 2 ? 0 : 138;
        }
      } else if (disX == 0) {
        var contentStyle = 0
      } else {
        var contentStyle = disX > 138 / 2 ? 138 : 0;
      }
    } else {
      contentStyle = 0
    }
    var lists = 'list[' + index + '].contentStyle'
    list.forEach((item, indexs) => {
      if (indexs != index) {
        list[indexs].contentStyle = 0
        list[indexs].transtion = true
      } else {
        list[indexs].transtion = false
      }
    })

    this.setData({
      [lists]: contentStyle,
      list,
    });
  },
  angle: function(start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
}))